<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAddUser">新增用户</el-button>
    </div>

    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" layout="inline">
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.uid" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
            <el-option label="专家" value="expert" />
            <el-option label="供应商" value="supplier" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table :data="users" border style="width: 100%" v-loading="loading">
        <el-table-column prop="uid" label="用户ID" width="120" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="realname" label="真实姓名" width="100" />
        <el-table-column prop="credit" label="信用分" width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)" 
              :disabled="scope.row.role === 'admin' && users.filter(u => u.role === 'admin').length <= 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="currentUser" label-width="80px">
        <el-form-item label="用户ID">
          <el-input v-model="currentUser.uid" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUser.role" style="width: 100%">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
            <el-option label="专家" value="expert" />
            <el-option label="供应商" value="supplier" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="currentUser.phone" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="currentUser.realname" />
        </el-form-item>
        <el-form-item label="信用分">
          <el-input-number v-model="currentUser.credit" :min="0" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers, updateUser, deleteUser } from '@/apis/admin.js'

const users = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')

const currentUser = ref({
  uid: '',
  username: '',
  role: 'user',
  phone: '',
  realname: '',
  credit: 60
})

const searchForm = reactive({
  uid: '',
  username: '',
  role: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

onMounted(() => {
  fetchUsers()
})

const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      uid: searchForm.uid || undefined,
      username: searchForm.username || undefined,
      role: searchForm.role || undefined
    }
    
    const response = await getUsers(params)
    if (response.code === 200) {
      users.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchUsers()
}

const handleReset = () => {
  searchForm.uid = ''
  searchForm.username = ''
  searchForm.role = ''
  pagination.currentPage = 1
  fetchUsers()
}

const handleAddUser = () => {
  isEdit.value = false
  dialogTitle.value = '新增用户'
  currentUser.value = {
    uid: '',
    username: '',
    role: 'user',
    phone: '',
    realname: '',
    credit: 60
  }
  dialogVisible.value = true
}

const handleEdit = (user) => {
  isEdit.value = true
  dialogTitle.value = '编辑用户'
  currentUser.value = { ...user }
  dialogVisible.value = true
}

const handleDelete = async (user) => {
  // 检查是否是最后一个管理员
  if (user.role === 'admin' && users.value.filter(u => u.role === 'admin').length <= 1) {
    ElMessage.warning('不能删除最后一个管理员')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteUser(user.uid)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchUsers()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    // 用户取消删除
  }
}

const saveUser = async () => {
  try {
    let response
    if (isEdit.value) {
      response = await updateUser(currentUser.value.uid, currentUser.value)
    } else {
      // 新增用户应该通过专门的接口，这里简化处理
      ElMessage.warning('新增用户功能需要通过注册页面完成')
      dialogVisible.value = false
      return
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      fetchUsers()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1 // 页大小改变时回到第一页
  fetchUsers()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUsers()
}

const getRoleTagType = (role) => {
  const typeMap = {
    admin: 'danger',
    expert: 'warning',
    supplier: 'success',
    user: 'info'
  }
  return typeMap[role] || 'info'
}

const getRoleText = (role) => {
  const textMap = {
    admin: '管理员',
    expert: '专家',
    supplier: '供应商',
    user: '普通用户'
  }
  return textMap[role] || '未知'
}
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>